package com.itheima.reggie.controller;


import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;

import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
public class EmployeeController {


    @Autowired
    private EmployeeService employeeService;

    //员工登录
    @PostMapping("employee/login")
    public ResultInfo login(@RequestBody Map<String,String> param, HttpSession session){
        //1.接受请求参数
        String username = param.get("username");
        String password = param.get("password");
        //2.调用service实现登录
        ResultInfo resultInfo = employeeService.login(username,password);
        //3.判断登陆状态
        if (resultInfo.getCode()==1){
            //将用户信息存入session
            session.setAttribute(Constant.SESSION_EMPLOYEE,resultInfo.getData());
        }
        //4.返回结果
        return resultInfo;
    }

    //员工退出
    @PostMapping("employee/logout")
    public ResultInfo logout(HttpSession session){
        //清除session
        session.invalidate();

        //返回结果
        return ResultInfo.success();
    }

    //员工列表
    @GetMapping("/employee/find")
    public ResultInfo find (String name){ //接受请求参数
        //调用service查询
        List<Employee> list = employeeService.findList(name);
        //返回结果
        return ResultInfo.success(list);
    }

    // 新增员工
    @PostMapping("/employee")
    public ResultInfo save (@RequestBody Employee employee){ //接受请求参数
        //调用service查询
        employeeService.save(employee);
        //返回结果
        return ResultInfo.success();
    }

    //回显员工
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id")Long id){
        // 2.调用service查询
        Employee employee = employeeService.findById(id);
        // 3.返回结果
        return ResultInfo.success(employee);
    }

    //修改员工
    @PutMapping("/employee")
    public ResultInfo update(@RequestBody Employee employee){
        // 2.调用serivce修改
        employeeService.update(employee);
        // 3.返回结果
        return ResultInfo.success();
    }

}
